package com.llz.leaveApply.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.llz.leaveApply.dto.Result;
import com.llz.leaveApply.entity.LeaveApply;
import com.llz.leaveApply.entity.User;
import com.llz.leaveApply.service.IUserService;
import com.llz.leaveApply.service.LeaveApplyService;
import com.llz.leaveApply.service.LeaveClearanceService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author llz
 * @since 2023-01-20
 */
@RestController
@RequestMapping("/leave-apply")
public class LeaveApplyController {
    @Resource
    LeaveApplyService leaveApplyService;
    @Resource
    LeaveClearanceService leaveClearanceService;
    @Resource
    IUserService userService;

    /**
     * 查询id用户的所有请假申请
     */
    @PostMapping("getUserAllApply")
    public Result getUserAllApply(@RequestParam("userNumber") String userNumber) {

        List<LeaveApply> leaveApplys = leaveApplyService.query().
                eq("user_number", userNumber).orderBy(true, true, "out_date").list();
        return Result.ok(leaveApplys);
    }


    /**
     * 根据请假单id 查询请假单详情 (基本信息，审批、销假情况）
     */
    @GetMapping("getApplyDetail")
    public Result getApplyDetail(@RequestParam int applyId) {

        LeaveApply leaveApply = leaveApplyService.query().eq("id", applyId).one();
        if (leaveApply == null) {
            return Result.fail("请假单不存在");
        }


        return Result.ok(leaveApply);
    }

    /**
     * 暂存一条请假单
     */
    @PostMapping("saveApply")
    @Transactional  //添加进事务 抛出异常的话 已近执行了的对数据库操作回滚
    public Result saveApply(@RequestBody LeaveApply leaveApply) {
        if (leaveApply != null) {
            leaveApply.setState(0);
        }
        //将之前暂存的请假单删掉保持，数据库库每个用户只有一条暂存记录
//    eq("user_number",leaveApply.getUserNumber()).eq("state",0)
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_number", leaveApply.getUserNumber());
        queryWrapper.eq("state", 0);
        leaveApplyService.remove(queryWrapper);
        boolean success = leaveApplyService.save(leaveApply);
        if (success) {//添加请假单成功

            return Result.ok("暂存请假单成功");
        }
        return Result.fail("暂存请假单失败");

    }

    /**
     * 添加一条请假单
     */
    @PostMapping("addApply")
    @Transactional  //添加进事务 抛出异常的话 已经执行了的对数据库操作回滚
    public Result addApply(@RequestBody LeaveApply leaveApply) {

//        todo 如果数据库中由 通过审核但是没未销假的请求则申请失败
        if (leaveApply != null) {
            leaveApply.setState(1);
        }
        boolean success = leaveApplyService.saveOrUpdate(leaveApply);
        if (success) {//添加请假单成功
            //添加到审批消息队列

            return Result.ok("提交请假单成功，等待审批中");
        }

        return Result.fail("提交请假单失败");
    }

    /**
     * 修改请假单信息 仅当请假单状态为0(暂存)或者 3（审批未通过）用户可操作
     *todo
     */

    /**
     * 获取最近一个 没通过的申请
     */

    @PostMapping("getLastRefuseApply")
    public Result getLastRefuseApply(@RequestParam("userNumber") String userNumber) {

        List<LeaveApply> leaveApplies = leaveApplyService.query().eq("state", 3).eq("user_number", userNumber)
                .orderBy(true, true, "out_date").list();
        LeaveApply leaveApply = new LeaveApply();
        if (leaveApplies.size() > 1) {
            leaveApply = leaveApplies.get(0);
        }
        //添加到审批消息队列

        return Result.ok(leaveApply);
    }

    //获取最后一个没有销假的申请
    @PostMapping("getLastNotClearanceApply")
    public Result getLastNotClearanceApply(@RequestParam("userNumber") String userNumber) {
//        未销假的话请假状态就是审核已通过
        List<LeaveApply> leaveApplies = leaveApplyService.query().eq("state", 2).eq("user_number", userNumber).orderBy(true, true, "out_date").list();
        LeaveApply leaveApply = null;
        if (leaveApplies.size() > 1) {
            leaveApply = leaveApplies.get(0);
//          User user=  userService.query().eq("user_number",leaveApply.getUserNumber()).one();
//            leaveApply.setApproverName(user.getName());
        }
        return Result.ok(leaveApply);
    }


    //    获取待当前用户审批的所有申请(包含请假和销假)
    @PostMapping("/getWaitApproval")
    public Result getWaitApproval(@RequestParam("userNumber") String userNumber) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("approver_id", userNumber);
        queryWrapper.in("state", 1, 6);

        return Result.ok(leaveApplyService.list(queryWrapper));
    }

    @PostMapping("/getLastwaitForApproverApply")
    public Result getLastwaitForApproverApply(@RequestParam("userNumber") String userNumber) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("approver_id", userNumber);
        queryWrapper.in("state", 1);
        queryWrapper.orderBy(true, true, "out_date");
        List<LeaveApply> applyList = leaveApplyService.list(queryWrapper);
        LeaveApply leaveApply = null;
        if (applyList.size() > 0) {
            leaveApply = applyList.get(0);
        }
        return Result.ok(leaveApply);
    }


//

    /**
     * 审核请假 销假
     *
     * @param userNumber
     * @param applyId
     * @param istongguo
     * @param mark
     * @param type       type 1 审核请假  2 审核销假
     * @return
     */
    @PostMapping("/shenhe/leave")
    Result shenhe(@RequestParam("userNumber") String userNumber,
                  @RequestParam("applyId") String applyId, @RequestParam("isTongguo") boolean istongguo, @RequestParam("remark") String mark, @RequestParam("type") int type) {
        String state = (type == 1 ? (istongguo ? "2" : "3") : (istongguo ? "4" : "7"));
        String sql = "remark='" + mark + "' ," + "state=" + state;
//        如果是审核销假 还需要额外  将销假申请设为 已审批
        if (type == 2) {
            leaveClearanceService.update().eq("approver", userNumber).eq("apply_id", applyId).setSql("yishenpi=" + 1).update();
        }

        return Result.ok(leaveApplyService.update().eq("approver_id", userNumber).eq("id", applyId).setSql(sql).update());
    }

    /**
     * 查询所有 在起止时间内经过某地的所有人的基本信息
     *
     * @param jingguo
     * @return
     */
    @PostMapping("/tongji")
    Result tongji(
            @RequestParam("date")
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                    Date date,
            @RequestParam("jingguo") String jingguo) {

//          先查出符合条件的人员id列表 在根据id列表查出人员信息 原始 sql
//            SELECT name, dept ,role from user  where user_number in
//            (SELECT DISTINCT  la.user_number FROM `leave_apply` la
//            where  '2023-10-12 12:45:00' BETWEEN  la.out_date and la.expected_return_date
//            and la.destination like '%南京%')  ;
//    Mybatis-plus中大于、小于的写法    https://blog.csdn.net/duihsa156165/article/details/110821433
        String like = "%" + jingguo + "%";
        List<LeaveApply> leaveApplies = leaveApplyService.query().select("user_number").like("destination", like).
                le("out_date", date).ge("expected_return_date", date).list();
//        取对象集合中的userNumber 属性
        List usernumbers = leaveApplies.stream().map(LeaveApply::getUserNumber).collect(Collectors.toList());
        List<User> users = null;
        if (usernumbers.size() > 0)            users = userService.query().select("name", "dept", "role").in("user_number", usernumbers.toArray()).list();
        return Result.ok(users);

    }

    void test(Collection collection){
     ((ArrayList)collection).get(1);

    }

}





